// src/user/user.service.ts
import { Model } from 'mongoose';
import * as bcrypt from 'bcrypt';
import { Injectable, Inject, LoggerService } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { JwtService } from '@nestjs/jwt';
import { User, UserDocument } from './schemas/user.schema';
import { CreateUserByEmailDto } from './dto/create-user.dto';
import { ErrorResponseException } from '../common/exceptions/custom-exception';
import { ValidationException } from 'src/common/exceptions/custom-exception';

@Injectable()
export class UserService {
  constructor(
    @InjectModel(User.name) private userModel: Model<UserDocument>,
    @Inject('CustomLogger') private readonly logger: LoggerService,
    private jwtService: JwtService,
  ) {}

  async createByEmail(
    createUserByEmailDto: CreateUserByEmailDto,
  ): Promise<User> {
    const saltRounds = 10;
    try {
      const createdUser = new this.userModel({
        username: createUserByEmailDto.username,
        password: await bcrypt.hash(createUserByEmailDto.password, saltRounds),
      });
      return await createdUser.save();
    } catch (error) {
      this.logger.error(error);
      if (error.code === 11000) {
        throw new ErrorResponseException(10001, 'username 重复；');
      }
      throw new ErrorResponseException(500, 'Internal server error');
    }
  }

  // async findById(id: string): Promise<User> {
  //   const findedUser = await this.userModel.findById(id);
  //   return findedUser;
  // }

  // 不验证密码
  async IsusersExist(username: string): Promise<boolean> {
    const findedUser = await this.userModel.findOne({
      username: username,
    });
    return Boolean(findedUser);
  }
  // 验证密码
  async findByUsername(username: string, password: string): Promise<User> {
    const findedUser = await this.userModel.findOne({
      username: username,
    });
    if (!findedUser) {
      return null;
    }
    // 验证密码
    const verifyPws = await bcrypt.compare(password, findedUser.password);
    if (!verifyPws) {
      throw new ValidationException('loginCheckFailInfo');
    }
    return findedUser;
  }
}
